package com.android.nodejs.livejs.activities;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.constants.AddMessageConstants;
import com.android.nodejs.livejs.constants.DisplayConstants;
import com.android.nodejs.livejs.utils.CommonUtil;

public class ChangePasswordActivity extends Activity {

	private EditText edtNewPassword;
	private EditText edtOldPassword;
	private EditText edtConfirmPassword;
	private ProgressDialog dialog;

//    private Socket socket = null;
//    private InputStream is = null;
//    private OutputStream os = null;

    private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_change_password);
		init();
		IntentFilter filterMessageChat = new IntentFilter("CHANGE_PASSWORD");
        getApplicationContext().registerReceiver(new MessageBroadCastReceiver(), filterMessageChat);
	}

	private void init() {
		dialog = new ProgressDialog(getApplicationContext());
		dialog.setMessage("Loading...Please wait!");
		dialog.setCancelable(false);

		edtNewPassword = (EditText) findViewById(R.id.edtNew_Password);
		edtOldPassword = (EditText) findViewById(R.id.edtOld_Password);
		edtConfirmPassword = (EditText) findViewById(R.id.edtConf_Password);
	}

	public void onClickSave(View v) {
		if ("".equals(edtNewPassword.getText().toString().trim()) 
				|| "".equals(edtOldPassword.getText().toString().trim())
				|| "".equals(edtConfirmPassword.getText().toString().trim())) {
			Toast.makeText(getApplicationContext(), "Please fill all fields!", Toast.LENGTH_LONG).show();
		} else {
			if (!MyApplication.USER_CURRENT.getPassword().equals(CommonUtil.convertToMD5(edtOldPassword.getText().toString().trim()))) {
				Toast.makeText(getApplicationContext(), "Wrong old password!", Toast.LENGTH_LONG).show();
			} else if (!edtConfirmPassword.getText().toString().trim().equals(edtNewPassword.getText().toString().trim())) {
				Toast.makeText(getApplicationContext(), "Confirm password do not match!", Toast.LENGTH_LONG).show();
			} else if(edtOldPassword.getText().toString().trim().equals(edtNewPassword.getText().toString().trim())) {
			    Toast.makeText(getApplicationContext(), "Old password and new password required different!", Toast.LENGTH_LONG).show();
			} else {
			    progressDialog = ProgressDialog.show(ChangePasswordActivity.this, "", "Changing your password...");
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            if (MyApplication.OS_CURRENT == null) {
                                if (progressDialog.isShowing()) {
                                    progressDialog.dismiss();
                                }
                                return;
                            }
                            Timer timer = new Timer();
                            timer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    if (progressDialog.isShowing()) {
                                        progressDialog.dismiss();
                                        Message msg = toastHandler.obtainMessage(2);
                                        toastHandler.sendMessage(msg);
                                        return;
                                    }
                                }
                            }, 20000);
                            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
                            w.write(AddMessageConstants.CHANGE_PASSWORD);
                            w.write(MyApplication.USER_CURRENT.getEmail()+"!!"+ CommonUtil.convertToMD5(edtNewPassword.getText().toString().trim()));
                            w.flush();
                            
                            if (progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                        } catch (SocketTimeoutException e) {
                            if (progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            Message msg = toastHandler.obtainMessage(2);
                            toastHandler.sendMessage(msg);
                            return;
                        } catch (UnknownHostException e) {
                            Log.d("UnknownHostException", e.getClass().getSimpleName() + ": " + e.getMessage());
                            e.printStackTrace();
                        } catch (IOException e) {
                            Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                            e.printStackTrace();
                        } catch (Exception e) {
                            Log.d("Exception", e.getClass().getSimpleName() + ": " + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }).start();
			}
		}
	}

	public void onClickBack(View v) {
		setResult(RESULT_CANCELED);
		finish();
	}
	
	/** Show Toast message */
    private Handler toastHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(getApplicationContext(), DisplayConstants.DIS_CHANG_PASSWORD_FAIL, Toast.LENGTH_LONG).show();
            } else if (msg.what == 1) {
                Toast.makeText(getApplicationContext(), DisplayConstants.DIS_CHANGED_PASSWORD_SUCCESS, Toast.LENGTH_LONG).show();
                // set new password to app
                MyApplication.USER_CURRENT.setPassword(CommonUtil.convertToMD5(edtNewPassword.getText().toString().trim()));
                // finish ChangePasswordActivity
                finish();
            } else if (msg.what == 2) {
                CommonUtil.dialogNotify(ChangePasswordActivity.this, DisplayConstants.DIS_CONNECT_SERVER_FAIL);
            }
        }
    };

    /**
     * receiver message broadcast
     * 
     * @author vuvt
     *
     */
    private class MessageBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("CHANGE_PASSWORD".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getStringExtra("msg"));
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            }
        }
    }
}